﻿using Roton.ZZT;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Roton.Input
{
    /// <summary>
    /// An Input class that attaches itself to Form events.
    /// </summary>
    public class InputForm : IInput
    {
        static private Encoding encoding = Encoding.GetEncoding(437);

        private bool alt;
        private bool altBuffer;
        private Queue<char> buffer;
        private bool ctrl;
        private bool ctrlBuffer;
        private Form form;
        private byte key;
        private bool shift;
        private bool shiftBuffer;

        public InputForm(Form form)
        {
            this.form = form;
            buffer = new Queue<char>();
            form.KeyDown += KeyDown;
            form.KeyPress += KeyPress;
        }

        ~InputForm()
        {
            form.KeyDown -= KeyDown;
            form.KeyPress -= KeyPress;
        }

        public bool AltPressed
        {
            get { return altBuffer; }
        }

        public bool CtrlPressed
        {
            get { return ctrlBuffer; }
        }

        void KeyDown(object sender, KeyEventArgs e)
        {
            alt = e.Alt;
            ctrl = e.Control;
            shift = e.Shift;
        }

        void KeyPress(object sender, KeyPressEventArgs e)
        {
            buffer.Enqueue(e.KeyChar);
        }

        public byte KeyPressed
        {
            get { return key; }
        }

        public void Poll()
        {
            if (buffer.Count > 0)
                key = encoding.GetBytes(new char[] { buffer.Dequeue() })[0]; // this feels too hacky.
            else
                key = 0;
        }

        public bool ShiftPressed
        {
            get { return shiftBuffer; }
        }
    }
}
